package io.plus.user_interface.common.utils;

import drds.common.$;
import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.user_interface.common.SessionContext;
import io.plus.user_interface.common.Status;
import io.plus.user_interface.common.UserConfiguration;
import io.plus.user_interface.common.io;
import io.plus.user_interface.common.packet.ChatMessage;
import io.plus.user_interface.common.packet.Command;
import io.plus.user_interface.common.packet.ResponseMessage;
import io.plus.user_interface.common.packet.User;
import io.plus.user_interface.common.protocol.PacketImpl;
import io.plus.utils.lock.ReadWriteLockSet;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatKit {
    public static ChatMessage toChatBody(byte[] body, AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        ChatMessage chatMessage = parseChatBody(body);
        if (chatMessage != null) {
            if ($.isNullOrEmpty(chatMessage.getFrom())) {
                SessionContext sessionContext = (SessionContext) asynchronousSocketChannelContext.getAttribute();
                User user = sessionContext.getClient().getUser();
                if (user != null) {
                    chatMessage.setFrom(user.getNick());
                } else {
                    chatMessage.setFrom(asynchronousSocketChannelContext.getId());
                }
            }
        }
        return chatMessage;
    }

    /**
     * 判断是否属于指定格式聊天消息;
     */
    private static ChatMessage parseChatBody(byte[] body) {
        if (body == null) {
            return null;
        }
        ChatMessage chatReqBody = null;
        try {
			/*String text = new String(body,HttpConst.CHARSET_NAME);
		    chatReqBody = JsonKit.toBean(text,ChatBody.class);
			if(chatReqBody != null){
				if(chatReqBody.getCreateTime() == null) {
					chatReqBody.setCreateTime(System.currentTimeMillis());
				}
				if(StringUtils.isEmpty(chatReqBody.getId())){
					chatReqBody.setId(UUIDSessionIdGenerator.instance.sessionId(null));
				}
				return chatReqBody;
			}*/
        } catch (Exception e) {
            //log.error(e.toString());
        }
        return chatReqBody;
    }

    /**
     * 判断是否属于指定格式聊天消息;
     *
     * @param bodyStr
     * @return
     */
    public static ChatMessage parseChatBody(String bodyStr) {
        if (bodyStr == null) {
            return null;
        }
        try {
            return parseChatBody(bodyStr.getBytes());
        } catch (Exception e) {
            //log.error(e);
        }
        return null;
    }

    /**
     * 聊天数据格式不正确响应包
     *
     * @param asynchronousSocketChannelContext
     * @return imPacket
     * @throws Exception
     */
    public static PacketImpl dataInCorrectRespPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage(Command.close_request, Status.C10002);
        PacketImpl respPacket = ImKit.convertResponsepPacket(responseMessage, asynchronousSocketChannelContext);
        respPacket.setStatus(Status.C10002);
        return respPacket;
    }

    /**
     * 聊天发送成功响应包
     */
    public static PacketImpl sendSuccessRespPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage(Command.close_request, Status.C10000);
        PacketImpl respPacket = ImKit.convertResponsepPacket(responseMessage, asynchronousSocketChannelContext);
        respPacket.setStatus(Status.C10000);
        return respPacket;
    }

    /**
     * 聊天用户不在线响应包
     */
    public static PacketImpl offlineRespPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        ResponseMessage responseMessage = new ResponseMessage(Command.chat_response, Status.C10001);
        PacketImpl respPacket = ImKit.convertResponsepPacket(responseMessage, asynchronousSocketChannelContext);
        respPacket.setStatus(Status.C10001);
        return respPacket;
    }

    /**
     * 判断用户是否在线
     */
    public static boolean isOnline(String userId, UserConfiguration userConfiguration) {
        boolean isStore = true;
        if (isStore) {
            return userConfiguration.getMessageHelper().isOnline(userId);
        }
        ReadWriteLockSet<AsynchronousSocketChannelContext> toChannelContexts = io.getChannelContextsByUserId(userId);
        return toChannelContexts != null && toChannelContexts.size() > 0;
    }

    /**
     * 获取双方会话ID
     */
    public static String sessionId(String from, String to) {
        if (from.compareTo(to) <= 0) {
            return from + "-" + to;
        } else {
            return to + "-" + from;
        }
    }
}
